package com.smartplatform.service.impl;

import com.smartplatform.cache.SceneCache;
import com.smartplatform.constants.ResultCode;
import com.smartplatform.exception.AddDateException;
import com.smartplatform.exception.QueryException;
import com.smartplatform.mapper.SysSceneMapper;
import com.smartplatform.pojo.CheckType;
import com.smartplatform.pojo.MyBaseUser;
import com.smartplatform.pojo.SysScene;
import com.smartplatform.service.SysSceneService;
import com.smartplatform.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * @Author 咕唧
 * @Date 2022/5/31 18:00
 * @Version 1.0
 */
@Service
@Transactional
public class SysSceneServiceImpl implements SysSceneService {

    private SceneCache sceneCache;

    private SysSceneMapper sysSceneMapper;

    @Autowired
    public void setSysSceneMapper(SysSceneMapper sysSceneMapper) {
        this.sysSceneMapper = sysSceneMapper;
    }

    @Autowired
    public void setSceneCache(SceneCache sceneCache) {
        this.sceneCache = sceneCache;
    }

    /**
     * 添加场景
     *
     * @param sysScene
     */
    @Override
    public void addSysScene(SysScene sysScene) {
        //校验数据
        Assert.isTrue(!sysScene.isEmpty(CheckType.ADD), () -> {
            throw new AddDateException("传递的数据不完整", ResultCode.DATA_NULL);
        });
        //获取当前登陆的用户信息
        MyBaseUser userInfo = SecurityUtils.getUserInfo(false);
        //查询缓存中的用户场景数据
        try {
            List<SysScene> sysSceneList = sceneCache.getUserSceneCache().get(userInfo.getUserId());
            long count = sysSceneList.stream()
                    .filter(sysScene1 -> sysScene.getSceneName().equals(userInfo.getUsername()))
                    .count();
            Assert.isTrue(count == 0, () -> {
                throw new QueryException("场景已经存在", ResultCode.SCENE_ALREADY_EXIST);
            });
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        //设置创建者
        sysScene.setCreateBy(userInfo.getUserId());
        //添加场景
        sysSceneMapper.addSysScene(sysScene);
    }

    @Override
    public List<SysScene> findAllSceneByUserId() {
        //获取当前登录的用户
        MyBaseUser userInfo = SecurityUtils.getUserInfo(false);
        //查询用户所有的场景
        List<SysScene> sysSceneList = null;
        try {
            sceneCache.getUserSceneCache().get(userInfo.getUserId());
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return sysSceneList;
    }
}
